from flask import Blueprint, request, jsonify
from models import db, User, UserSchema

users_bp = Blueprint('users', __name__)
user_schema = UserSchema()
users_schema = UserSchema(many=True)


########################
# md5 in python
########################
import random
import hashlib

# 获取由4位随机大小写字母、数字组成的salt值
def create_salt(length = 4):
    salt = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    len_chars = len(chars) - 1
    for i in range(length):
        # 每次从chars中随机取一位
        salt += chars[random.randint(0, len_chars)]
    return salt
if 0:
    userSalt = create_salt(6)
    print("1. userSalt:", userSalt)

# 获取原始密码+salt的md5值  
def create_md5(pwd, salt):  
    md5_obj = hashlib.md5()
    md5_obj.update( (str(pwd) + salt).encode('utf-8') )
    return md5_obj.hexdigest()
if 0:
    #pass1=create_md5("123456", "") #e10adc3949ba59abbe56e057f20f883e
    pass1=create_md5("123456", userSalt)
    print("2. pass1:", pass1)
    # 和shell结果一致，注意加-n去掉最后的换行符 $ echo -n 123456 | md5sum # e10adc3949ba59abbe56e057f20f883e  -

from config import Config
SYS_SALT = Config.SYS_SALT





@users_bp.route('/', methods=['POST'])
def create_user():
    username = request.json.get('username')
    email = request.json.get('email')
    password_hash = request.json.get('password_hash')
    
    new_user = User(username=username, email=email, password_hash=password_hash)
    db.session.add(new_user)
    db.session.commit()
    
    return user_schema.jsonify(new_user), 201


@users_bp.route('/', methods=['GET'])
def get_users():
    users = User.query.all()
    return users_schema.jsonify(users), 200




########################
# user login
########################

@users_bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    user = User.query.filter_by(username=username).first()
    if user and user.password_hash == create_md5(password, SYS_SALT):
        #access_token = create_access_token(identity={'user_id': user.user_id})
        access_token = create_md5(user.user_id, SYS_SALT)
        return jsonify({'access_token':access_token, "user_id": user.user_id, "username": user.username} ), 200
    return jsonify({'msg': 'Bad username or password'}), 401


# 验证token是否合法: 用户id存在，token正确
@users_bp.route('/validateToken', methods=['POST'])
def validate_token():
    data = request.json  # 从请求体获取 JSON 数据
    user_id = data.get('user_id')  # 获取 user_id

    token = None
    if 'Authorization' in request.headers:
        handler = request.headers['Authorization'].split(" ")[0]
        if create_md5(handler, "") != "ec9a7070dfdeac000605a4e48e2911e6":
            print("This is an unsafe communication!")

        token = request.headers['Authorization'].split(" ")[1]
        if token and token == create_md5(user_id, SYS_SALT):
            user = User.query.filter_by(user_id=user_id).first()
            if user:
                return jsonify({'message': 'Valid token and UID!'}), 200

    return jsonify({'message': 'Invalid token or UID!'}), 401
